package com.leyou.order.interceptors;

import com.leyou.common.auth.JwtUtils;
import com.leyou.common.auth.Payload;
import com.leyou.common.auth.UserInfo;
import com.leyou.common.constants.UserTokenConstants;
import com.leyou.common.utils.CookieUtils;
import com.leyou.order.utils.UserHolder;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;

/**
 * @author 虎哥
 */
public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {
            // 获取token
            String token = CookieUtils.getCookieValue(request, UserTokenConstants.COOKIE_NAME);
            // 解析用户
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, UserInfo.class);
            UserInfo user = payload.getUserInfo();
            // 保存用户
            UserHolder.setUser(user);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("解析用户信息失败！", e);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserHolder.removeUser();
    }
}
